package com.shaoshaohuo.app.ui.ec;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.adapter.SpecificationAdapter;
import com.shaoshaohuo.app.constant.ExtraName;
import com.shaoshaohuo.app.entity.BaseEntity;
import com.shaoshaohuo.app.entity.PurchaseDetail;
import com.shaoshaohuo.app.entity.PurchaseDetailEntity;
import com.shaoshaohuo.app.entity.Specification;
import com.shaoshaohuo.app.utils.SpecificationDataUtil;
import com.shaoshaohuo.app.utils.ViewUtil;
import com.shaoshaohuo.app.utils.im.IMFactory;
import com.shaoshaohuo.app.framework.ActivityCollector;
import com.shaoshaohuo.app.net.RequestService;
import com.shaoshaohuo.app.net.HttpRequest.RequestListener;
import com.shaoshaohuo.app.ui.BaseActivity;
import com.shaoshaohuo.app.ui.EvaluationActivity;
import com.shaoshaohuo.app.view.TopbarView;
import com.shaoshaohuo.app.utils.DeviceHelper;
import com.shaoshaohuo.app.utils.StringHelper;

import java.util.List;
import java.util.Map;

/**
 * 采购订单详情
 */
public class PurchaseOrderDetailActivity extends BaseActivity {

    private TopbarView mTopbarView;

    private View mDetailTopLayout;
    private View mDetailBottomLayout;
    
    private TextView mOrderNumberText;
    private TextView mTimeText;
    private TextView mStatusText;
    
    private TextView mSupplyNameText;
    private TextView mProductNameText;
    private ImageView mCallPhoneImage;
    private TextView mPriceText;
    private TextView mNumText;
    private TextView mTotalText;
    private TextView mContactNameText;
    private TextView mContactPhoneText;
    private TextView mAddressText;
    
    private Button mLeftButton;
    private Button mRightButton;
    
    private String orderid;

	private PurchaseDetail data;

	private ImageView mCallChatImage;

    private GridView gv_specification;
    private FrameLayout fl_specification;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_purchase_order_detail);
        initData();
        initView();
        setUpView();
        requestData();
	}

	private void initData() {
		orderid = getIntent().getStringExtra(ExtraName.orderid);
	}

	private void requestData() {
	    startLoadingDialog();
	    RequestService.getInstance().getPurchaseOrderDetail(this, orderid, PurchaseDetailEntity.class, new RequestListener() {
            
            @Override
            public void onSuccess(int requestCode, BaseEntity resultData) {
                dismissLoadingDialog();
                if(resultData.isOk()){
                    PurchaseDetailEntity entity = (PurchaseDetailEntity) resultData;
                    updataUi(entity);
                }else{
                    showToast(resultData.getMsg());
                }
            }
            
            @Override
            public void onFailed(int requestCode, Exception error, String msg) {
                dismissLoadingDialog();
                showToast(R.string.please_check_network);
            }
        });
    }

    protected void updataUi(PurchaseDetailEntity entity) {
    	data = entity.getData();
    	mOrderNumberText.setText("订单编号："+data.getOrderid());
    	mTimeText.setText(StringHelper.formatDateMinute(data.getCtime()));
    	
//    	状态 -1买家取消订单 -2卖家取消订单，0 还没有选择供应商 1买家同意待付款 2待发货 3运输中 4已完成
    	switch (Integer.parseInt(data.getStatus())) {
		case -1:
			mStatusText.setText("订单取消");
			mLeftButton.setVisibility(View.GONE);
			mRightButton.setVisibility(View.GONE);
			break;
		case -2:
			mStatusText.setText("订单取消");
			mLeftButton.setVisibility(View.GONE);
			mRightButton.setVisibility(View.GONE);
			break;
		case 0:
//			mStatusText.setText("订单确认");
//			mLeftButton.setVisibility(View.GONE);
//			mRightButton.setVisibility(View.VISIBLE);
//			mRightButton.setText("放弃购买");
			break;
		case 1:
			mStatusText.setText("待付款");
			mLeftButton.setVisibility(View.VISIBLE);
			mRightButton.setVisibility(View.VISIBLE);
            mLeftButton.setText("放弃购买");
            mRightButton.setText("付款");
            mLeftButton.setOnClickListener(new OnClickListener() {
                
                @Override
                public void onClick(View v) {
                    showGiveUpBuyDialog(data);
                }
            });
            mRightButton.setOnClickListener(new OnClickListener() {
                
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(PurchaseOrderDetailActivity.this,PayEcActivity.class);
                    intent.putExtra(ExtraName.orderid, data.getOrderid());
                    intent.putExtra(ExtraName.totalPrice, Double.parseDouble(data.getTotal()));
                    intent.putExtra(ExtraName.action, PayEcActivity.PAY_ACTION_SUPPLY);
                    startActivity(intent);
                }
            });
			break;
		case 2:
			mStatusText.setText("待发货");
			mLeftButton.setVisibility(View.GONE);
			mRightButton.setVisibility(View.VISIBLE);
			mRightButton.setText("放弃购买");
			mRightButton.setOnClickListener(new OnClickListener() {
                
                @Override
                public void onClick(View v) {
                    showGiveUpBuyDialog(data);
                }
            });
			break;
		case 3:
			mStatusText.setText("运输中");
			mLeftButton.setVisibility(View.GONE);
			mRightButton.setVisibility(View.VISIBLE);
			mRightButton.setText("确认收货");
			mRightButton.setOnClickListener(new OnClickListener() {
                
                @Override
                public void onClick(View v) {
                    showReceiverDialog(data);
                }
            });
			break;
		case 4:
//			mLeftButton.setVisibility(View.GONE);
//			if(Data.getBuydisscuz().equals("1")){
//				mRightButton.setVisibility(View.GONE);
//			}else{
//				mRightButton.setVisibility(View.VISIBLE);
//				mRightButton.setText("评价");
//			}
			
			if ("1".equals(data.getBuydisscuz())) {
				mStatusText.setText("已完成，已评价");
                mLeftButton.setVisibility(View.GONE);
                mRightButton.setVisibility(View.VISIBLE);
                mRightButton.setText("删除订单");
                mRightButton.setOnClickListener( new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        showDeleteDialog(data);
                    }
                });
            } else {
            	mStatusText.setText("已完成，未评价");
                mLeftButton.setVisibility(View.VISIBLE);
                mRightButton.setVisibility(View.VISIBLE);
                mLeftButton.setText("评价");
                mLeftButton.setOnClickListener( new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(PurchaseOrderDetailActivity.this, EvaluationActivity.class);
                        intent.putExtra(ExtraName.type, EvaluationActivity.EVALUATION_TYPE_PURCHASE);
                        intent.putExtra(ExtraName.orderid, data.getOrderid());
                        startActivity(intent);
                    }
                });
                mRightButton.setText("删除订单");
                mRightButton.setOnClickListener( new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        showDeleteDialog(data);
                    }
                });
            }
			
			break;
		}
    	
    	mSupplyNameText.setText(data.getRealname());
    	mProductNameText.setText(data.getTitle());
    	mCallPhoneImage.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                DeviceHelper.callPhone(PurchaseOrderDetailActivity.this, data.getMobile());
            }
        });
    	mCallChatImage.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                IMFactory.openChat(PurchaseOrderDetailActivity.this, data.getUserid());
            }
        });
    	mPriceText.setText(data.getPrice() + "元/" + data.getUnit());
    	mNumText.setText(data.getNum()+data.getUnit());
    	mTotalText.setText("合计："+data.getTotal()+"元");
    	mContactNameText.setText(data.getReceiver());
    	mContactPhoneText.setText(data.getRecemobile());
    	mAddressText.setText(data.getReceiveaddress());

        if (data.specifications != null && data.specifications.size() > 0) {

            Map<Specification, List<Specification>> specificationMap = SpecificationDataUtil.list2map(data.specifications);
            gv_specification.setAdapter(new SpecificationAdapter(this, gv_specification, specificationMap));
        }else{
            fl_specification.setVisibility(View.GONE);
        }
    }
    
    private void showDeleteDialog(final PurchaseDetail data) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("确认删除订单?");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            
            @Override
            public void onClick(DialogInterface dialog, int which) {
                deleteOrder(data);
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        builder.create().show();
    }
    protected void deleteOrder(final PurchaseDetail data) {
        startLoadingDialog();
        RequestService.getInstance().deletePurchaseOrder(this, data.getOrderid(), BaseEntity.class, new RequestListener() {
                
                @Override
                public void onSuccess(int requestCode, BaseEntity resultData) {
                    dismissLoadingDialog();
                    if(resultData.isOk()){
                        showToast("订单删除成功");
                        finish();
//                        requestData();
//                        list.remove(Data);
//                        notifyDataSetChanged();
                    }else{
                        showToast(resultData.getMsg());
                    }
                }
                
                @Override
                public void onFailed(int requestCode, Exception error, String msg) {
                    dismissLoadingDialog();
                    showToast(R.string.please_check_network);
                }
            });
    }
    
    protected void receiverGoods(final PurchaseDetail data) {
        startLoadingDialog();
        RequestService.getInstance().receivePurchaseOrder(this, data.getOrderid(), BaseEntity.class, new RequestListener() {
                
                @Override
                public void onSuccess(int requestCode, BaseEntity resultData) {
                    dismissLoadingDialog();
                    if(resultData.isOk()){
                        showToast("确认收货成功");
                        requestData();
//                        list.remove(item);
//                        notifyDataSetChanged();
                    }else{
                        showToast(resultData.getMsg());
                    }
                }
                
                @Override
                public void onFailed(int requestCode, Exception error, String msg) {
                    dismissLoadingDialog();
                    showToast(R.string.please_check_network);
                }
            });
    }

    
    private void showReceiverDialog(final PurchaseDetail data) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("确认货物已收到?");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            
            @Override
            public void onClick(DialogInterface dialog, int which) {
                receiverGoods(data);
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        builder.create().show();
    }
    
    private void showGiveUpBuyDialog(final PurchaseDetail data) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("确认放弃?");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                giveUpBuy(data);
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        builder.create().show();
    }
    
    protected void giveUpBuy(final PurchaseDetail data) {
            startLoadingDialog();
            RequestService.getInstance().cancelPurchaseOrder(this, data.getOrderid(), BaseEntity.class, new RequestListener() {
                
                @Override
                public void onSuccess(int requestCode, BaseEntity resultData) {
                    dismissLoadingDialog();
                    if(resultData.isOk()){
                        showToast("取消报价成功");
                        requestData();
                    }else{
                        showToast(resultData.getMsg());
                    }
                }
                
                @Override
                public void onFailed(int requestCode, Exception error, String msg) {
                    dismissLoadingDialog();
                    showToast(R.string.please_check_network);
                }
            });
    }
    
	private void initView() {
        mTopbarView = (TopbarView) this.findViewById(R.id.topbar);
        mDetailTopLayout = this.findViewById(R.id.layout_top);
        mDetailBottomLayout = this.findViewById(R.id.layout_bottom);
        
        mOrderNumberText = (TextView) this.findViewById(R.id.textview_order_number);
        mTimeText = (TextView) this.findViewById(R.id.textview_time);
        mStatusText = (TextView) this.findViewById(R.id.textview_status);
        mSupplyNameText = (TextView) this.findViewById(R.id.textview_gonghuoshang);
        mProductNameText = (TextView) this.findViewById(R.id.textview_product);
        mCallChatImage = (ImageView) this.findViewById(R.id.imageview_call_chat);
        mCallPhoneImage = (ImageView) this.findViewById(R.id.imageview_call_phone);
        mPriceText = (TextView) this.findViewById(R.id.textview_price);
        mNumText = (TextView) this.findViewById(R.id.textview_count);
        mTotalText = (TextView) this.findViewById(R.id.textview_total);
        mContactNameText = (TextView) this.findViewById(R.id.textview_contact_name);
        mContactPhoneText = (TextView) this.findViewById(R.id.textview_contact_phone);
        mAddressText = (TextView) this.findViewById(R.id.textview_address);

        gv_specification = (GridView) findViewById(R.id.gv_specification);
        fl_specification = (FrameLayout) findViewById(R.id.fl_specification);
        
        mLeftButton = (Button) this.findViewById(R.id.button_left);
        mRightButton = (Button) this.findViewById(R.id.button_right);
    }

    private void setUpView() {
        mTopbarView.setCenterText("订单详情");
        mTopbarView.setLeftView(true, true);

//        mDetailTopLayout.setOnClickListener(mDetailTopListener);
//        mDetailBottomLayout.setOnClickListener(mDetailBottomListener);
    }

    private OnClickListener mDetailTopListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
        	if(data==null){
        		return;
        	}
        	if("1".equals(data.getTypeid())){
        		Intent intent = new Intent(PurchaseOrderDetailActivity.this, SupplyDetailActivity.class);
        		intent.putExtra(ExtraName.id, data.getInfoid());
        		startActivity(intent);
        	}else{
        		Intent intent = new Intent(PurchaseOrderDetailActivity.this, PurchaseDetailActivity.class);
        		intent.putExtra(ExtraName.id, data.getInfoid());
        		startActivity(intent);
        	}
        }
    };
    private OnClickListener mDetailBottomListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
        	Intent intent = new Intent(PurchaseOrderDetailActivity.this, PurchaseDetailActivity.class);
    		intent.putExtra(ExtraName.id, data.getInfoid());
    		startActivity(intent);
        }
    };
    
    @Override
    public void finish() {
    	if(ActivityCollector.activities.size()==1){
    		Intent launchIntent = getPackageManager().
                    getLaunchIntentForPackage(getPackageName());
    		startActivity(launchIntent);
    	}
    	super.finish();
    }
}
